load("@fbcode_macros//build_defs:native_rules.bzl", "buck_filegroup", "buck_genrule")
load("@fbsource//tools/build_defs:rust_library.bzl", "rust_library")

oncall("build_infra")

# Runs lalrpop on grammar.lalrpop to generate grammar.rs
buck_genrule(
    name = "grammar",
    srcs = ["src/syntax/grammar.lalrpop"],
    out = ".",
    # We can't use $SRCS, because in Buck1 that is absolute, and lalrpop --out-dir only works with relative sources
    cmd = "$(exe fbsource//third-party/rust:lalrpop-lalrpop) src/syntax/grammar.lalrpop --out-dir $OUT",
)

buck_filegroup(
    name = "testcases",
    srcs = glob([
        "src/**/*.golden",
        "testcases/**",
    ]),
)

rust_library(
    name = "starlark_syntax",
    srcs = glob(["src/**/*.rs"]),
    env = {
        # Allows src/syntax/mod.rs to include grammar.rs generated by lalrpop.
        "OUT_DIR": "$(location :grammar)/src",
    },
    rustc_flags = [
        "--cfg=rust_nightly",
    ],
    test_deps = [
        "fbsource//third-party/rust:serde_json",
    ],
    test_env = {
        # Some of our tests include testcase files relative to CARGO_MANIFEST_DIR.
        # This is a hack that allows both `cargo test` and `buck test` to work.
        "CARGO_MANIFEST_DIR": "$(location :testcases)",
        "OUT_DIR": "$(location :grammar)/src",
    },
    visibility = [
        # Do not use this crate internally in Meta.
        # `starlark` crate has public API.
        # If you need some feature requiring working with syntax tree, like a linter,
        # please implement it inside the `starlark` crate.
        # For codemods, use libCST.
        "//buck2/starlark-rust/...",
        # For faster incremental compilation of buck2,
        # we pull `starlark::Error` from this crate rather than from `starlark`.
        "//buck2/app/buck2_error/...",
    ],
    deps = [
        "fbsource//third-party/rust:annotate-snippets",
        "fbsource//third-party/rust:anyhow",
        "fbsource//third-party/rust:derivative",
        "fbsource//third-party/rust:derive_more",
        "fbsource//third-party/rust:lalrpop-util",
        "fbsource//third-party/rust:logos",
        "fbsource//third-party/rust:lsp-types",
        "fbsource//third-party/rust:memchr",
        "fbsource//third-party/rust:num-bigint",
        "fbsource//third-party/rust:num-traits",
        "fbsource//third-party/rust:once_cell",
        "fbsource//third-party/rust:thiserror",
        "//buck2/allocative/allocative:allocative",
        "//buck2/gazebo/dupe:dupe",
        "//buck2/starlark-rust/starlark_map:starlark_map",
    ],
)
